package cn.iocoder.yudao.module.system.service.normalquestioncontent;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.module.system.controller.admin.normalquestioncontent.vo.NormalQuestionContentPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.normalquestioncontent.vo.NormalQuestionContentSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.gugu.CeeMajorDO;
import cn.iocoder.yudao.module.system.dal.dataobject.normalquestion.NormalQuestionDO;
import cn.iocoder.yudao.module.system.dal.dataobject.normalquestioncontent.NormalQuestionContentDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.UserAssetsDO;
import cn.iocoder.yudao.module.system.dal.mysql.gugu.CeeMajorMapper;
import cn.iocoder.yudao.module.system.dal.mysql.normalquestion.NormalQuestionMapper;
import cn.iocoder.yudao.module.system.dal.mysql.normalquestioncontent.NormalQuestionContentMapper;
import cn.iocoder.yudao.module.system.dal.mysql.user.UserAssetsMapper;
import cn.iocoder.yudao.module.system.service.user.UserAssetsService;
import cn.iocoder.yudao.module.system.util.baidu.BaiduAiUtils;
import com.fhs.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.*;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;


import javax.annotation.Resource;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.util.baidu.BaiduAiUtils.APP_BUILDER_TOKEN;

/**
 * AI 报告 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class NormalQuestionContentServiceImpl implements NormalQuestionContentService {

    @Resource
    private NormalQuestionContentMapper normalQuestionContentMapper;

    @Resource
    private NormalQuestionMapper normalQuestionMapper;

    @Resource
    UserAssetsMapper userAssetsMapper;

    @Resource
    private UserAssetsService userAssetsService;

    @Resource
    private CeeMajorMapper ceeMajorMapper;

    @Override
    public Long createNormalQuestionContent(NormalQuestionContentSaveReqVO createReqVO) {
        // 插入
        NormalQuestionContentDO normalQuestionContent = BeanUtils.toBean(createReqVO, NormalQuestionContentDO.class);
        normalQuestionContentMapper.insert(normalQuestionContent);
        // 返回
        return normalQuestionContent.getId();
    }

    @Override
    public void updateNormalQuestionContent(NormalQuestionContentSaveReqVO updateReqVO) {
        // 校验存在
        validateNormalQuestionContentExists(updateReqVO.getId());
        // 更新
        NormalQuestionContentDO updateObj = BeanUtils.toBean(updateReqVO, NormalQuestionContentDO.class);
        normalQuestionContentMapper.updateById(updateObj);
    }

    @Override
    public void deleteNormalQuestionContent(Long id) {
        // 校验存在
        validateNormalQuestionContentExists(id);
        // 删除
        normalQuestionContentMapper.deleteById(id);
    }

    private void validateNormalQuestionContentExists(Long id) {
        if (normalQuestionContentMapper.selectById(id) == null) {
            throw exception(new ErrorCode(404, "AI 报告不存在"));
        }
    }

    @Override
    public NormalQuestionContentDO getNormalQuestionContent(Long id) {
        return normalQuestionContentMapper.selectById(id);
    }

    @Override
    public PageResult<NormalQuestionContentDO> getNormalQuestionContentPage(NormalQuestionContentPageReqVO pageReqVO) {
        NormalQuestionDO normalQuestionDO = normalQuestionMapper.selectOne("id", pageReqVO.getQuestionId());
//        if (normalQuestionDO != null) {
//            if (!"2".equals(normalQuestionDO.getParentType())&&!"4".equals(normalQuestionDO.getParentType())&&!"5".equals(normalQuestionDO.getParentType()))
//            //访问该内容时，将扣减当日免费可看次数
//            {
//                // 检查用户内容会员剩余次数
//                userAssetsService.validateUserContentMembership(Long.valueOf(pageReqVO.getUserId()));
//            }
//        }


        //discus转化
        if (!StringUtil.isEmpty(pageReqVO.getDsCus())) {
            if ("2".equals(pageReqVO.getDsCus())) {
                pageReqVO.setDsCus("请给出各档次的学校推荐");
            } else if ("3".equals(pageReqVO.getDsCus())) {
                pageReqVO.setDsCus("请给出各档次学生的就业前景");
            }
        }

        pageReqVO.setType(pageReqVO.getVersion() == null ? "1" : "2");


        PageResult<NormalQuestionContentDO> normalQuestionContentDOPageResult = normalQuestionContentMapper.selectPage(pageReqVO);
        List<NormalQuestionContentDO> normalQuestionContentDOS = normalQuestionContentDOPageResult.getList();
        if (normalQuestionContentDOS == null || normalQuestionContentDOS.isEmpty()) {
            NormalQuestionContentDO normalQuestionContentDO = new NormalQuestionContentDO();
            normalQuestionContentDO.setQuestionId(pageReqVO.getQuestionId());
            normalQuestionContentDO.setContent("");
            normalQuestionContentDO.setDs(normalQuestionDO.getDs());
            normalQuestionContentDO.setDsCus(pageReqVO.getDsCus());
            normalQuestionContentDO.setVersion(pageReqVO.getVersion());
            normalQuestionContentDO.setType(pageReqVO.getType());
            normalQuestionContentDO.setParentType(normalQuestionDO.getParentType());
            normalQuestionContentMapper.insert(normalQuestionContentDO);
            normalQuestionContentDOPageResult = normalQuestionContentMapper.selectPage(pageReqVO);
            normalQuestionContentDOS = normalQuestionContentDOPageResult.getList();
        }

        if (normalQuestionContentDOS != null && !normalQuestionContentDOS.isEmpty()) {
            for (NormalQuestionContentDO normalQuestionContentDO : normalQuestionContentDOS) {
                if (StringUtil.isEmpty(normalQuestionContentDO.getContent())) {
                    System.setProperty("APPBUILDER_TOKEN", APP_BUILDER_TOKEN);
                    String appId;

                    switch (normalQuestionContentDO.getParentType()) {
                        //行业趋势
                        case "1":
                            if ((pageReqVO.getVersion() == null)) {
                                appId = BaiduAiUtils.Version.TREND_2.getAppId();
                                break;
                            } else {
                                appId = BaiduAiUtils.Version.TREND.getAppId();
                                break;
                            }
                            //志愿100问
                        case "2":
                            appId = BaiduAiUtils.Version.GRE_100.getAppId();
                            break;
                        //热门专业
                        case "3":
                            if (pageReqVO.getVersion() != null && pageReqVO.getVersion() == 2) {
                                appId = BaiduAiUtils.Version.HOT_2.getAppId();
                                break;
                            } else if (pageReqVO.getVersion() != null && pageReqVO.getVersion() == 3) {
                                appId = BaiduAiUtils.Version.HOT_3.getAppId();
                                break;
                            }
                            appId = BaiduAiUtils.Version.HOT.getAppId();
                            break;
                        //慎选专业
                        case "4":
                            appId = BaiduAiUtils.Version.CHOICE.getAppId();
                            break;
                        default:
                            appId = BaiduAiUtils.Version.NORMAL.getAppId();
                    }


                    String q = normalQuestionContentDO.getDs();
                    String dsCus = normalQuestionContentDO.getDsCus();
                    if (!StringUtil.isEmpty(dsCus)) {
                        if (normalQuestionContentDO.getVersion() == null) {
                            normalQuestionContentDO.setVersion(1);
                        }
                        switch (normalQuestionContentDO.getVersion()) {
                            case 1:
                                q += "推荐该专业" + dsCus;
                                break;
                            case 2:
                                q += "按各个档次学校推荐，不要输出表格形式的内容，全部用文本段落形式输出。";
                                break;
                            case 3:
                                q += "列出各档次学生前景，不要输出表格形式的内容，全部用文本段落形式输出。";
                                break;
                        }
                        normalQuestionContentDO.setType("2");
                    }

                    normalQuestionContentDO.setDs(q);
                    String s = BaiduAiUtils.processQueryOpenApi(appId, q, false);
                    String s1 = BaiduAiUtils.mdConvertTHtml(s == null ? "" : s);
                    normalQuestionContentDO.setContent(s1);

                    normalQuestionContentMapper.updateById(normalQuestionContentDO);
                }
            }
        }
        return normalQuestionContentMapper.selectPage(pageReqVO);
    }

    @Override
    public List<NormalQuestionContentDO> getCategoryList(String parentType) {
        return Collections.emptyList();
    }

    @Override
    public NormalQuestionContentDO getNormalQuestionContentByName(String name) {
        NormalQuestionContentDO normalQuestionContentDO = normalQuestionContentMapper.selectOne("question", name, "type", "9");
        if (normalQuestionContentDO == null) {
            NormalQuestionContentDO normalQuestionContentDO1 = new NormalQuestionContentDO();
            normalQuestionContentDO1.setQuestion(name);
            normalQuestionContentDO1.setType("9");
            normalQuestionContentDO1.setContent("");
            normalQuestionContentMapper.insert(normalQuestionContentDO1);
            normalQuestionContentDO = normalQuestionContentMapper.selectOne("question", name, "type", "9");
        }
        if (StringUtil.isEmpty(normalQuestionContentDO.getContent())) {
            System.setProperty("APPBUILDER_TOKEN", APP_BUILDER_TOKEN);
            String appId = BaiduAiUtils.Version.MAJOR.getAppId();
            String q = normalQuestionContentDO.getQuestion() + "专业";
            String s = BaiduAiUtils.processQueryOpenApi(appId, q, false);
            String s1 = BaiduAiUtils.mdConvertTHtml(s == null ? "" : s);
            normalQuestionContentDO.setContent(s1);
            normalQuestionContentMapper.updateById(normalQuestionContentDO);
            normalQuestionContentDO = normalQuestionContentMapper.selectOne("question", name, "type", "9");
        }
        return normalQuestionContentDO;
    }

    @Override
    public int generateMajorContents() {
        log.info("开始生成专业内容...");
        int count = 0;

        // 设置 APPBUILDER_TOKEN 环境变量
        System.setProperty("APPBUILDER_TOKEN", APP_BUILDER_TOKEN);
        String appId = BaiduAiUtils.Version.MAJOR.getAppId();

        // 查询所有专业信息
        List<CeeMajorDO> majors = ceeMajorMapper.selectList();
        log.info("共查询到 {} 个专业信息", majors.size());

        for (CeeMajorDO major : majors) {
            try {
                // 检查是否已存在该专业的内容
                String majorName = major.getMajorName();
                NormalQuestionContentDO existingContent = normalQuestionContentMapper.selectOne(
                        "question", majorName, "type", "9");

                if (existingContent != null && !StringUtil.isEmpty(existingContent.getContent())) {
                    log.info("专业 [{}] 的内容已存在，跳过处理", majorName);
                    continue;
                }

                // 创建或更新内容
                NormalQuestionContentDO contentDO;
                if (existingContent == null) {
                    // 创建新记录
                    contentDO = new NormalQuestionContentDO();
                    contentDO.setQuestion(majorName);
                    contentDO.setType("9"); // 专业类型
                    contentDO.setContent("");
                    contentDO.setVersion(1);

                    // 构建指令
                    StringBuilder instruction = new StringBuilder();
                    instruction.append("请详细介绍").append(majorName).append("专业\n");

                    contentDO.setDs(instruction.toString());

                    // 保存到数据库
                    normalQuestionContentMapper.insert(contentDO);
                    contentDO = normalQuestionContentMapper.selectOne("question", majorName, "type", "9");
                } else {
                    // 使用已有记录
                    contentDO = existingContent;

                    // 如果没有指令，添加指令
                    if (StringUtil.isEmpty(contentDO.getDs())) {
                        StringBuilder instruction = new StringBuilder();
                        instruction.append("请详细介绍").append(majorName).append("专业\n");
                        contentDO.setDs(instruction.toString());
                        normalQuestionContentMapper.updateById(contentDO);
                    }
                }

                // 调用百度AI生成内容
                log.info("正在为专业 [{}] 生成内容...", majorName);
                String query = contentDO.getDs();
                String response = BaiduAiUtils.processQueryOpenApi(appId, query, false);

                if (response != null && !response.isEmpty()) {
                    // 转换为HTML并保存
                    String htmlContent = BaiduAiUtils.mdConvertTHtml(response);
                    contentDO.setContent(htmlContent);
                    normalQuestionContentMapper.updateById(contentDO);
                    count++;
                    log.info("专业 [{}] 内容生成成功", majorName);
                } else {
                    log.warn("专业 [{}] 内容生成失败，API返回为空", majorName);
                }

                // 避免API调用过于频繁，添加短暂延迟
                Thread.sleep(1000);

            } catch (Exception e) {
                log.error("处理专业 [{}] 时发生错误", major.getMajorName(), e);
            }
        }

        log.info("专业内容生成完成，共成功处理 {} 个专业", count);
        return count;
    }
}